<template>
  <view class="page">
    <!-- 页面头部 -->
    <view class="header">
      <view class="search-bar">
        <uni-icons type="search" color="#999" size="18" />
        <input class="search-input" placeholder="搜索菜品" />
      </view>
    </view>
    
    <!-- 主要内容区域 - 左右联动布局 -->
    <view class="main-content">
      <!-- 左侧分类列表 -->
      <scroll-view 
        class="category-sidebar" 
        scroll-y 
        scroll-with-animation
        :scroll-top="leftScrollTop"
      >
        <view 
          v-for="(category, index) in categories" 
          :key="category._id" 
          class="category-item"
          :class="{ active: activeCategoryIndex === index }"
          @click="switchCategory(index)"
        >
          <view class="category-icon">
            <image 
              v-if="getCategoryImage(category)" 
              class="category-image" 
              :src="getCategoryImage(category)" 
              mode="aspectFill" 
            />
            <uni-icons 
              v-else
              :type="getCategoryIconType(category)" 
              :color="activeCategoryIndex === index ? '#FF6B35' : '#666'" 
              :size="32" 
            />
          </view>
          <view class="category-name">{{ category.name }}</view>
        </view>
      </scroll-view>
      
      <!-- 右侧菜品列表 -->
      <scroll-view 
        class="dish-content" 
        scroll-y 
        scroll-with-animation
        :scroll-into-view="currentScrollId"
        @scroll="handleRightScroll"
      >
        <!-- 分类菜品区域 -->
        <view 
          v-for="(category, index) in categories" 
          :key="category._id" 
          class="category-section"
          :id="`category-${index}`"
        >
          <view class="category-title">{{ category.name }}</view>
          <view class="dish-list">
            <view 
              v-for="dish in getDishesByCategory(category._id)" 
              :key="dish._id" 
              class="dish-card"
              @click="handleDishClick(dish)"
            >
              <view class="dish-image-wrapper">
                <image class="dish-image" :src="getDishImage(dish)" mode="aspectFill" />
                <view class="favorite-btn" @click.stop="toggleFavorite(dish)">
                  <uni-icons 
                    :type="isFavorited(dish._id) ? 'heart-filled' : 'heart'" 
                    :color="isFavorited(dish._id) ? '#ef4444' : '#ffffff'" 
                    :size="20" 
                  />
                </view>
              </view>
              <view class="dish-info">
                <view class="dish-header">
                  <view class="dish-name">{{ dish.name }}</view>
                  
                </view>
                <view class="dish-desc">{{ dish.description || '暂无描述' }}</view>
                <view class="dish-footer">
                  <view class="dish-tags">
                    <view class="spice-badge" :class="getSpicinessClass(dish.spiciness)">{{ getSpicinessText(dish.spiciness) }}</view>
                    <text v-if="dish.is_recommended" class="recommend-tag">推荐</text>
                    <view class="dish-price">{{ dish.price }}</view>
                  </view>
                  <text class="sales">月售{{ dish.sales || 0 }}</text>
                </view>
                <view class="dish-actions">
                  <view v-if="getItemCount(dish._id) === 0">
                    <button class="cart-btn" @click.stop="addToCart(dish)">
                      <uni-icons type="cart" size="20" color="#FF6B35" />
                    </button>
                  </view>
                  <view v-else class="qty-group" @click.stop>
                    <button class="qty-btn minus" @click.stop="decrementItem(dish)">
                      <uni-icons type="minus" :size="18" color="#6B7280" />
                    </button>
                    <text class="qty-count">{{ getItemCount(dish._id) }}</text>
                    <button class="qty-btn plus" @click.stop="incrementItem(dish)">
                      <uni-icons type="plus" :size="18" color="#111827" />
                    </button>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
    
    
  </view>
</template>

<script setup>
import { ref, onMounted, reactive, watch, nextTick } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import cart from '../../common/cart.js'
import { getImageSrc } from '../../common/image.js'
import { getSpicinessText, getSpicinessClass } from '../../common/dish.js'
import { addFavorite, removeFavorite, batchCheckFavorites } from '../../common/favorite.js'
// #ifdef H5
 
// #endif

const categories = ref([])
const dishes = ref([])
const activeCategoryIndex = ref(0)
const currentScrollId = ref('category-0')
const leftScrollTop = ref(0)
const categoryPositions = reactive({})
const isUserClicking = ref(false) // 标记是否是用户点击分类
const favoriteMap = ref({})
 
// 辣度展示使用通用工具

// 已点数量
const countMap = ref({})
function refreshCounts() {
  const list = cart.getCart()
  const map = {}
  list.forEach(it => { map[it.id] = Number(it.count) || 0 })
  countMap.value = map
}
function getItemCount(id) {
  return countMap.value[id] || 0
}
function incrementItem(dish) {
  const current = getItemCount(dish._id)
  cart.updateCount(dish._id, current + 1)
  refreshCounts()
  cart.syncTabBadge(2)
}
function decrementItem(dish) {
  const current = getItemCount(dish._id)
  const next = current - 1
  if (next <= 0) {
    cart.removeItem(dish._id)
  } else {
    cart.updateCount(dish._id, next)
  }
  refreshCounts()
  cart.syncTabBadge(2)
}

// 分类图标映射
const categoryIcons = {
  '热销': 'fire',
  '推荐': 'star',
  '主食': 'food',
  '小吃': 'snack',
  '饮品': 'drink',
  '套餐': 'gift',
  '甜品': 'heart',
  '汤类': 'soup'
}

// 加载分类数据
const loadCategories = async () => {
  try {
    const res = await uniCloud.callFunction({
      name: 'food-categories',
      data: { 
        action: 'get-categories', 
        data: { 
          page: 1, 
          pageSize: 100, 
          status: '', 
          sortField: 'sort', 
          sortOrder: 'asc' 
        } 
      }
    })
    
    if (res.result && res.result.code === 200) {
      const list = (res.result.data && res.result.data.list) || []
      categories.value = list.filter(item => Number(item.status) === 1)
      // 加载菜品数据
      loadDishes()
    }
  } catch (err) {
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    })
  }
}

// 加载菜品数据
const loadDishes = async () => {
  try {
    const res = await uniCloud.callFunction({
      name: 'food-dishes',
      data: { 
        action: 'get-dishes', 
        data: { 
          page: 1, 
          pageSize: 200, 
          status: 1
        } 
      }
    })
    
    if (res.result && res.result.code === 200) {
      dishes.value = (res.result.data && res.result.data.list) || []
      
      // 批量检查收藏状态
      await loadFavoritesStatus()
    }
  } catch (err) {
  }
}

// 加载收藏状态
async function loadFavoritesStatus() {
  if (dishes.value.length === 0) return
  const dishIds = dishes.value.map(item => item._id)
  favoriteMap.value = await batchCheckFavorites(dishIds)
}

// 切换收藏状态
async function toggleFavorite(dish) {
  const dishId = dish._id
  const currentFav = favoriteMap.value[dishId]
  
  if (currentFav && currentFav.isFavorite) {
    // 取消收藏
    const result = await removeFavorite(currentFav.favorite_id)
    if (result.success) {
      uni.showToast({ title: result.message, icon: 'success' })
      favoriteMap.value[dishId] = { isFavorite: false, favorite_id: null }
    }
    // 失败时不显示提示（工具函数已处理登录引导）
  } else {
    // 添加收藏
    const result = await addFavorite(dish)
    if (result.success) {
      uni.showToast({ title: result.message, icon: 'success' })
      favoriteMap.value[dishId] = { isFavorite: true, favorite_id: result.favorite_id }
    }
    // 失败时不显示提示（工具函数已处理登录引导）
  }
}

// 检查是否已收藏
function isFavorited(dishId) {
  return favoriteMap.value[dishId]?.isFavorite || false
}

// 获取分类图标类型
const getCategoryIconType = (category) => {
  const name = category.name
  for (const [key, value] of Object.entries(categoryIcons)) {
    if (name.includes(key)) {
      return value
    }
  }
  return 'list'
}

// 获取分类图片
const getCategoryImage = (category) => {
  if (category?.image) {
    if (typeof category.image === 'string') return category.image.trim()
    if (Array.isArray(category.image) && category.image.length) {
      const first = category.image[0]
      if (typeof first === 'string') return first.trim()
      if (first && typeof first.url === 'string') return first.url.trim()
    }
    if (typeof category.image === 'object' && category.image.url) {
      return category.image.url.trim()
    }
  }
  return null
}

// 根据分类获取菜品
const getDishesByCategory = (categoryId) => {
  return dishes.value.filter(dish => dish.category_id === categoryId)
}

// 获取菜品图片
const getDishImage = (dish) => getImageSrc(dish?.image) || '/static/placeholder-dish.png'

// 切换分类
const switchCategory = (index) => {
  // 设置用户点击标记
  isUserClicking.value = true
  
  // 更新active状态
  activeCategoryIndex.value = index
  
  // 设置滚动到对应分类
  currentScrollId.value = `category-${index}`
  
  // 计算左侧滚动位置
  const itemHeight = 100 // 每个分类项的高度
  const visibleItems = 5 // 可见分类项数量
  const targetPosition = Math.max(0, index * itemHeight - (visibleItems - 1) * itemHeight / 2)
  leftScrollTop.value = targetPosition
  
  // 800ms后重置点击标记，确保滚动动画完成
  setTimeout(() => {
    isUserClicking.value = false
  }, 800)
}

// 处理右侧滚动
const handleRightScroll = (e) => {
  const scrollTop = e.detail.scrollTop
  
  // 如果没有位置信息，直接返回
  if (Object.keys(categoryPositions).length === 0) return
  
  // 计算当前应该激活的分类
  let currentIndex = 0
  
  // 累计高度区间法：找到滚动位置所在的分类区间
  for (let i = 0; i < categories.value.length; i++) {
    const startTop = categoryPositions[`category-${i}`]
    const endTop = categoryPositions[`category-${i + 1}`] || categoryPositions['category-end']
    
    if (startTop !== undefined && endTop !== undefined) {
      // 精确判断：startTop <= scrollTop < endTop
      if (scrollTop >= startTop && scrollTop < endTop) {
        currentIndex = i
        break
      }
    }
  }
  
  // 处理边界情况：顶部
  if (scrollTop <= 0) {
    currentIndex = 0
  }
  // 处理边界情况：底部
  const totalHeight = categoryPositions['category-end'] || 0
  if (scrollTop >= totalHeight - 1) {
    currentIndex = categories.value.length - 1
  }
  
  // 只有当不是用户点击触发的滚动时才更新active状态
  if (!isUserClicking.value && currentIndex !== activeCategoryIndex.value) {
    activeCategoryIndex.value = currentIndex
    
    // 更新左侧分类滚动位置
    const itemHeight = 100
    const visibleItems = 5
    const targetPosition = Math.max(0, currentIndex * itemHeight - (visibleItems - 1) * itemHeight / 2)
    leftScrollTop.value = targetPosition
  }
}

// 获取分类位置信息（累计高度区间法）
const getCategoryPositions = () => {
  return new Promise((resolve) => {
    const query = uni.createSelectorQuery()
    
    // 直接获取所有分类块的尺寸信息
    query.selectAll('.category-section').boundingClientRect()
    
    query.exec((res) => {
      // selectAll 返回的结果在 res[0]
      const rects = res && res[0]
      if (!rects || rects.length === 0) {
        resolve()
        return
      }
      
      // 清空之前的位置信息
      Object.keys(categoryPositions).forEach(key => {
        delete categoryPositions[key]
      })
      
      // 使用累计高度计算每个分类的起始 top（相对于 scroll-view 内容）
      let cumulativeTop = 0
      rects.forEach((rect, index) => {
        const height = rect?.height || 0
        categoryPositions[`category-${index}`] = cumulativeTop
        cumulativeTop += height
      })
      // 记录总高度，作为最后一个区间的边界
      categoryPositions['category-end'] = cumulativeTop
      
      resolve()
    })
  })
}

// 处理菜品点击
const handleDishClick = (dish) => {
  uni.navigateTo({
    url: `/pages/dish-detail/dish-detail?id=${dish._id}`
  })
}

// 添加到已点
const addToCart = (dish) => {
  cart.addItem(dish, 1)
  uni.showToast({ title: '已加入已点', icon: 'success' })
  cart.syncTabBadge(2)
  refreshCounts()
}
 
// 数据加载后重新计算分类位置（DOM 渲染完成后）
watch([categories, dishes], async () => {
  if (categories.value.length > 0 && dishes.value.length > 0) {
    await nextTick()
    setTimeout(async () => {
      await getCategoryPositions()
      
      // 检查是否需要切换到指定分类
      const targetCategoryId = uni.getStorageSync('targetCategoryId')
      if (targetCategoryId) {
        const targetIndex = categories.value.findIndex(cat => cat._id === targetCategoryId)
        if (targetIndex !== -1) {
          switchCategory(targetIndex)
          // 清除存储的目标分类 ID
          uni.removeStorageSync('targetCategoryId')
        }
      }
    }, 0)
  }
})

onMounted(() => {
  loadCategories()
  refreshCounts()
})

onShow(() => {
  loadCategories()
  cart.syncTabBadge(2)
  refreshCounts()
  // 页面显示后重新获取分类位置，使用更可靠的延迟策略
  setTimeout(async () => {
    await getCategoryPositions()
    // 如果菜品数据已经加载，再次获取位置信息确保准确性
    if (dishes.value.length > 0) {
      setTimeout(async () => {
        await getCategoryPositions()
      }, 500)
    }
  }, 800)
})
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 100rpx; /* 为底部导航栏留出空间 */
}

/* 头部搜索栏 */
.header {
  background: #fff;
  padding: 20rpx 32rpx;
  border-bottom: 1rpx solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 10;
}

.search-bar {
  background: #f5f5f5;
  border-radius: 32rpx;
  padding: 20rpx 24rpx;
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  background: transparent;
}

/* 主要内容区域 */
.main-content {
  display: flex;
  height: calc(100vh - 180rpx);
}

/* 左侧分类栏 */
.category-sidebar {
  width: 200rpx;
  background: #f8f8f8;
  border-right: 1rpx solid #e8e8e8;
}

.category-item {
  padding: 24rpx 16rpx;
  display: flex;
  align-items: center;
  gap: 16rpx;
  border-bottom: 1rpx solid #f0f0f0;
  transition: all 0.3s ease;
  
  &.active {
    background: #fff;
    color: #FF6B35;
    font-weight: 600;
    position: relative;
    
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 6rpx;
      height: 40rpx;
      background: #FF6B35;
      border-radius: 0 4rpx 4rpx 0;
    }
  }
  
  &:active {
    background: #f0f0f0;
  }
}

.category-icon {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 48rpx;
  height: 48rpx;
  flex-shrink: 0;
}

.category-image {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.category-name {
  font-size: 26rpx;
  line-height: 1.2;
  flex: 1;
  text-align: left;
}

/* 右侧菜品内容 */
.dish-content {
  flex: 1;
  background: #fff;
}

.category-section {
  padding: 32rpx;
}

.category-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 24rpx;
  padding-bottom: 16rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.dish-list {
  display: flex;
  flex-direction: column;
  gap: 32rpx;
}

.dish-card {
  display: flex;
  gap: 24rpx;
  padding: 24rpx;
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.98);
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  }
}

.dish-image-wrapper {
  position: relative;
  width: 160rpx;
  height: 160rpx;
  flex-shrink: 0;
}

.dish-image {
  width: 100%;
  height: 100%;
  border-radius: 12rpx;
  background: #f5f5f5;
}

/* 收藏按钮 */
.favorite-btn {
  position: absolute;
  top: 8rpx;
  right: 8rpx;
  width: 40rpx;
  height: 40rpx;
  background: rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(8rpx);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
  transition: all 0.2s ease;
  
  &:active {
    transform: scale(0.9);
  }
}

.dish-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.dish-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8rpx;
}

.dish-name {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  flex: 1;
}

.cart-btn {
  width: 48rpx;
  height: 48rpx;
  border: none;
  background: transparent;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s ease;
  
  &:active {
    background: #f5f5f5;
    transform: scale(0.9);
  }
}

 
.dish-desc {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 16rpx;
  line-height: 1.4;
}

.dish-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dish-actions { display: flex; justify-content: flex-end; margin-top: 12rpx; }
/* 数量按钮组（紧凑） */
.qty-group { display: inline-flex; align-items: center; gap: 8rpx; padding: 4rpx 6rpx; border-radius: 999rpx; background: rgba(250, 204, 21, 0.12); border: 1rpx solid #FDE68A; box-shadow: 0 3rpx 8rpx rgba(0,0,0,0.08); }
.qty-btn { width: 44rpx; height: 44rpx; border-radius: 50%; display: flex; align-items: center; justify-content: center; background: transparent; border: none; box-shadow: none; }
.qty-btn.minus { background: transparent; border: none; }
.qty-btn.plus { background: transparent; border: none; }
.qty-count { min-width: 32rpx; text-align: center; font-size: 26rpx; color: #111827; }

.dish-tags {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.spice-badge { padding: 6rpx 14rpx; border-radius: 999rpx; font-size: 22rpx; font-weight: 600; line-height: 1; }
.spice-badge.mild { background: #f1f5f9; color: #334155; }
.spice-badge.light { background: #fde68a; color: #92400e; }
.spice-badge.medium { background: #fca5a5; color: #7f1d1d; }
.spice-badge.hot { background: #ef4444; color: #ffffff; }

.dish-price {
  font-size: 36rpx;
  font-weight: 600;
  color: #FF6B35;
}

.recommend-tag {
  font-size: 20rpx;
  color: #FF6B35;
  background: rgba(255, 107, 53, 0.1);
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
  border: 1rpx solid #FF6B35;
}

.sales {
  font-size: 22rpx;
  color: #999;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 100rpx 32rpx;
  color: #999;
}

.empty-icon {
  margin-bottom: 24rpx;
}

.empty-text {
  font-size: 28rpx;
}
</style>